package grpc

import (
	"gitee.com/sdynasty/yogurt/selector"
	"gitee.com/sdynasty/yogurt/transport"
	"google.golang.org/grpc/metadata"
)

type Transport struct {
	endpoint    string
	operation   string
	reqHeader   headerCarrier
	replyHeader headerCarrier
	nodeFilters []selector.NodeFilter
}

func (tr *Transport) Kind() transport.Kind {
	return transport.KindGRPC
}

func (tr *Transport) Endpoint() string {
	return tr.endpoint
}

func (tr *Transport) Operation() string {
	return tr.operation
}

func (tr *Transport) RequestHeader() transport.Header {
	return tr.replyHeader
}

func (tr *Transport) ReplyHeader() transport.Header {
	return tr.replyHeader
}

func (tr *Transport) NodeFilters() []selector.NodeFilter {
	return tr.nodeFilters
}

type headerCarrier metadata.MD

func (mc headerCarrier) Get(key string) string {
	vals := metadata.MD(mc).Get(key)
	if len(vals) > 0 {
		return vals[0]
	}
	return ""
}

func (mc headerCarrier) Set(key string, value string) {
	metadata.MD(mc).Set(key, value)
}

func (mc headerCarrier) Keys() []string {
	keys := make([]string, 0, len(mc))
	for k := range metadata.MD(mc) {
		keys = append(keys, k)
	}
	return keys
}
